package com.android.lightcontroler;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.Charlie.Utils.LightController;
import com.Charlie.Utils.LightController.MsgCallback;

import android.app.Activity;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.RelativeLayout.LayoutParams;

public class LightListActivity extends Activity implements OnClickListener,
		OnItemClickListener, MsgCallback {

	private Button mBackBtn;
	private Button mFindBtn;
	private Button mAddBtn;
	private ListView mListView;
	public LightAdapter adapter;
//	private PopupWindow mAddPopWindow;
	private Dialog mAddDialog;

	private EditText mAddrInput;
	private EditText mNameInput;
	private Button mConfirmBtn;
	private Button mCancelBtn;
	private Button mCheckAllBtn;
	private boolean isAllBtn;

	public List<Map<String, String>> mDataList;

	public static LightListActivity mLightListActivity;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		mLightListActivity = this;
		setContentView(R.layout.light_list_page);
		initView();
		initDataList();

		LightController.shareInstance().setMsgCallback(this);
	}

	/**
	 * 初始化view
	 */
	protected void initView() {
		mBackBtn = (Button) findViewById(R.id.back_btn);
		mFindBtn = (Button) findViewById(R.id.find_btn);
		mAddBtn = (Button) findViewById(R.id.add_btn);
		mCheckAllBtn = (Button) findViewById(R.id.all_btn);
		isAllBtn = true;
//		mCheckNoneBtn = (Button) findViewById(R.id.none_btn);
		
		mBackBtn.setOnClickListener(this);
		mFindBtn.setOnClickListener(this);
		mAddBtn.setOnClickListener(this);
		mCheckAllBtn.setOnClickListener(this);
//		mCheckNoneBtn.setOnClickListener(this);
		
		mListView = (ListView) findViewById(R.id.light_listview);

		mListView.setOnItemClickListener(this);

		View popView = LayoutInflater.from(LightListActivity.this).inflate(
				R.layout.add_dialog_view, null);
		mAddrInput = (EditText) popView.findViewById(R.id.addr_view);
		mNameInput = (EditText) popView.findViewById(R.id.name_view);
		mConfirmBtn = (Button) popView.findViewById(R.id.confirm_btn);
		mCancelBtn = (Button) popView.findViewById(R.id.cancel_btn);
		mConfirmBtn.setOnClickListener(this);
		mCancelBtn.setOnClickListener(this);

		// mAddPopWindow = new PopupWindow(popView, dip2px(this, 300),
		// LayoutParams.WRAP_CONTENT);
		// mAddPopWindow.setFocusable(true);
		// mAddPopWindow.setOutsideTouchable(true);
		// mAddPopWindow.setAnimationStyle(R.style.AnimationPop);
		// mAddPopWindow.setBackgroundDrawable(new ColorDrawable());

		mAddDialog = new Dialog(this, R.style.CustomDialogStyle);
		ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(dip2px(this,
				300), LayoutParams.WRAP_CONTENT);
		mAddDialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
		mAddDialog.addContentView(popView, params);
	}

	protected void initDataList() {
		if (mDataList == null) {
			mDataList = new ArrayList<Map<String, String>>();
		}
		mDataList.clear();

		LightDataHelper dbHelper = new LightDataHelper(this);
		SQLiteDatabase db = dbHelper.getReadableDatabase();
		Cursor cursor = db.query(LightDataHelper.TABLE_NAME, null, null, null,
				null, null, null);
		if (cursor.moveToFirst()) {
			do {
				String addr = cursor.getString(cursor
						.getColumnIndex(LightDataHelper.COL_ADDRESS));
				String name = cursor.getString(cursor
						.getColumnIndex(LightDataHelper.COL_NAME));
				String id = cursor.getString(cursor
						.getColumnIndex(LightDataHelper.COL_ID));

				Map<String, String> map = new HashMap<String, String>();
				map.put(LightDataHelper.COL_ADDRESS, addr);
				map.put(LightDataHelper.COL_NAME, name);
				map.put(LightDataHelper.COL_ID, id);
				mDataList.add(map);
			} while (cursor.moveToNext());
		}

		try {
			cursor.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			db.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (adapter == null) {
			adapter = new LightAdapter();
			mListView.setAdapter(adapter);
		}
		adapter.notifyDataSetChanged();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		menu.add(1, 1, 1, "Delete");
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case 1:
			if (adapter != null && !adapter.isEmpty()) {
				List<String> idList = new ArrayList<String>();
				for (int i = 0, count = adapter.getCount(); i < count; i++) {
					CheckBox cb = (CheckBox) mListView.getChildAt(i)
							.findViewById(R.id.light_checkbox);
					if (cb.isChecked()) {
						String id = mDataList.get(i)
								.get(LightDataHelper.COL_ID);
						idList.add(id);
					}
				}
				deleteData(idList);
				initDataList();
			}
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.back_btn:
			goBack();
			break;
		case R.id.find_btn:
			if (LightController.shareInstance().isConnected()) {
				LightController.shareInstance().findTheLight();
			}
			break;
		case R.id.add_btn:
			// mAddPopWindow.getContentView().setTag(null);
			// mAddPopWindow.showAtLocation(getWindow().getDecorView(),
			// Gravity.CENTER, 0, 0);
			mAddrInput.setText(null);
			mNameInput.setText(null);
			mConfirmBtn.setTag(null);
			mAddDialog.show();
			break;
		case R.id.confirm_btn:
			String addr = mAddrInput.getText().toString().trim();
			if ("".equals(addr)) {
				Toast.makeText(LightListActivity.this,
						"Please input the address.", Toast.LENGTH_SHORT).show();
				return;
			}
			String name = mNameInput.getText().toString().trim();
			if ("".equals(name)) {
				Toast.makeText(LightListActivity.this,
						"Please input the name of the light.",
						Toast.LENGTH_SHORT).show();
				return;
			}

			/* 判断id 是否存在，如果存在就进行修改，不存在就新增 */
			// String light_id = (String)
			// mAddPopWindow.getContentView().getTag();
			String light_id = (String) mConfirmBtn.getTag();
			if (light_id == null) {
				addData(addr, name);
			} else {
				upDate(addr, name, light_id);
			}

			initDataList();
		case R.id.cancel_btn:
			mAddrInput.setText(null);
			mNameInput.setText(null);
			// mAddPopWindow.dismiss();
			mAddDialog.dismiss();
			break;
		case R.id.all_btn:
			if (adapter == null || adapter.isEmpty()) {
				return;
			}
				for (int i = 0; i < adapter.getCount(); i++) {
					CheckBox cb = (CheckBox) mListView.getChildAt(i).findViewById(
							R.id.light_checkbox);
					cb.setChecked(isAllBtn);
				}
				mCheckAllBtn.setText(isAllBtn ? "None" :"All");	
				isAllBtn = !isAllBtn;
			break;
	
		default:
			break;
		}
	}

	/**
	 * 增加数据
	 * 
	 * 2014-4-18
	 */
	protected void addData(String addr, String name) {
		LightDataHelper dbHelper = new LightDataHelper(this);
		SQLiteDatabase db = dbHelper.getWritableDatabase();

		Cursor cursor = db.query(LightDataHelper.TABLE_NAME, null,
				LightDataHelper.COL_ADDRESS + "='" + addr + "'", null, null,
				null, null);
		if (!cursor.moveToNext()) {

			ContentValues contentValue = new ContentValues();
			contentValue.put(LightDataHelper.COL_ADDRESS, addr);
			contentValue.put(LightDataHelper.COL_NAME, name);
			db.insert(LightDataHelper.TABLE_NAME, null, contentValue);
			Toast.makeText(LightListActivity.this, "Add successful!",
					Toast.LENGTH_SHORT).show();
		}
		try {
			db.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 更改数据
	 * 
	 * 2014-4-18 廖朝瑞
	 */
	protected void upDate(String addr, String name, String id) {

		LightDataHelper dbHelper = new LightDataHelper(this);
		SQLiteDatabase db = dbHelper.getWritableDatabase();

		ContentValues values = new ContentValues();
		values.put(LightDataHelper.COL_NAME, name);
		values.put(LightDataHelper.COL_ADDRESS, addr);

		db.update(LightDataHelper.TABLE_NAME, values, LightDataHelper.COL_ID
				+ "=" + id, null);

		try {
			db.close();
			Toast.makeText(LightListActivity.this, "Update successful!",
					Toast.LENGTH_SHORT).show();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 删除
	 * 
	 * @param idList
	 *            2014-4-19
	 */
	protected void deleteData(List<String> idList) {
		if (idList == null || idList.size() < 1) {
			return;
		}
		LightDataHelper dbHelper = new LightDataHelper(this);
		SQLiteDatabase db = dbHelper.getWritableDatabase();

		for (int i = 0; i < idList.size(); i++) {
			db.delete(LightDataHelper.TABLE_NAME, LightDataHelper.COL_ID + "="
					+ idList.get(i), null);
		}

		try {
			db.close();
			Toast.makeText(this, "Delete successful!", Toast.LENGTH_SHORT)
					.show();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 返回
	 * 
	 * 2014-4-19
	 */
	protected void goBack() {
		Intent resultIntent = new Intent();

		if (adapter != null && !adapter.isEmpty()) {
			List<String> idList = new ArrayList<String>();
			List<String> nameList = new ArrayList<String>();
			List<String> addrList = new ArrayList<String>();

			for (int i = 0; i < adapter.getCount(); i++) {
				CheckBox cb = (CheckBox) mListView.getChildAt(i).findViewById(
						R.id.light_checkbox);
				if (cb.isChecked()) {
					String id = mDataList.get(i).get(LightDataHelper.COL_ID);
					idList.add(id);
					String name = mDataList.get(i)
							.get(LightDataHelper.COL_NAME);
					nameList.add(name);
					String address = mDataList.get(i).get(
							LightDataHelper.COL_ADDRESS);
					addrList.add(address);
				}
			}

			if (idList.size() > 0) {
				String ids[] = new String[idList.size()];
				String addrs[] = new String[idList.size()];

				for (int i = 0, size = idList.size(); i < size; i++) {
					ids[i] = idList.get(i);
					addrs[i] = addrList.get(i);
				}

				resultIntent.putExtra("ids", ids);
				resultIntent.putExtra("addr", addrs);

				if (ids.length == 1) {
					resultIntent.putExtra("name", nameList.get(0));
				}
			}
		}

		/* 如果什么都没选中，就发一个空 */
		setResult(Activity.RESULT_OK, resultIntent);
		LightController.shareInstance().setMsgCallback(null);
		finish();
	}

	public class LightAdapter extends BaseAdapter {

		LayoutInflater inflater;
		List<String> checkIdList;

		public LightAdapter() {
			inflater = LayoutInflater.from(LightListActivity.this);
			checkIdList = new ArrayList<String>();
			String[] ids = getIntent().getStringArrayExtra("ids");

			if (ids != null) {
				for (int i = 0; i < ids.length; i++) {
					checkIdList.add(ids[i]);
				}
			}
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			if (mDataList == null) {
				return 0;
			} else {
				return mDataList.size();
			}
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return mDataList.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHolder holder;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = inflater.inflate(R.layout.light_list_item, null);
				holder.lightCheckBox = (CheckBox) convertView
						.findViewById(R.id.light_checkbox);
				holder.addressView = (TextView) convertView
						.findViewById(R.id.address_view);
				holder.nameView = (TextView) convertView
						.findViewById(R.id.name_view);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			Map<String, String> map = mDataList.get(position);
			final String id = map.get(LightDataHelper.COL_ID);
			String addr = map.get(LightDataHelper.COL_ADDRESS);
			String name = map.get(LightDataHelper.COL_NAME);
			holder.addressView.setText(addr);
			holder.nameView.setText(name);

			holder.lightCheckBox
					.setOnCheckedChangeListener(new OnCheckedChangeListener() {

						@Override
						public void onCheckedChanged(CompoundButton buttonView,
								boolean isChecked) {
							// TODO Auto-generated method stub
							if (isChecked && !checkIdList.contains(id)) {
								checkIdList.add(id);
							} else if (!isChecked && checkIdList.contains(id)) {
								checkIdList.remove(id);
							}
						}
					});

			if (checkIdList.contains(id)) {
				holder.lightCheckBox.setChecked(true);
			} else {
				holder.lightCheckBox.setChecked(false);
			}

			return convertView;
		}

	}

	class ViewHolder {
		CheckBox lightCheckBox;
		TextView addressView;
		TextView nameView;
	}

	public static int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub

		String light_id = mDataList.get(position).get(LightDataHelper.COL_ID);
		String name = mDataList.get(position).get(LightDataHelper.COL_NAME);
		String address = mDataList.get(position).get(
				LightDataHelper.COL_ADDRESS);

		mAddrInput.setText(address);
		mNameInput.setText(name);
		// mAddPopWindow.getContentView().setTag(light_id);
		// mAddPopWindow.showAtLocation(getWindow().getDecorView(),
		// Gravity.CENTER, 0, 0);
		mConfirmBtn.setTag(light_id);
		mAddDialog.show();
	}

	private String findAddr;

	@Override
	public void findLight(String addr) {
		// TODO Auto-generated method stub
		findAddr = addr;
		/* 回调不是在主线程，所以需要回到主线程 */
		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				addData(findAddr, findAddr);
				initDataList();
			}
		});
	}
}